package server.main.utils;

import org.apache.commons.lang.ObjectUtils;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @auther MingHsZzz
 * @Date 2022/9/26  19:21
 * @project leetcode
 * @description
 */
public class Code128Utils {


    public static byte[] generateBarCode128(String message, Double height, Double width, boolean withQuietZone, boolean hideText) {
        Code128Bean bean = new Code128Bean();
        // 分辨率
        int dpi = 512;
        // 设置两侧是否留白
        bean.doQuietZone(withQuietZone);

        // 设置条形码高度和宽度
        bean.setBarHeight((double) ObjectUtils.defaultIfNull(height, 9.0D));
        if (width != null) {
            bean.setModuleWidth(width);
        }
        // 设置文本位置（包括是否显示）
        if (hideText) {
            bean.setMsgPosition(HumanReadablePlacement.HRP_NONE);
        }
        // 设置图片类型
        String format = "image/png";

        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        BitmapCanvasProvider canvas = new BitmapCanvasProvider(ous, format, dpi,
                BufferedImage.TYPE_BYTE_BINARY, false, 0);

        // 生产条形码
        bean.generateBarcode(canvas, message);
        try {
            canvas.finish();
        } catch (IOException e) {
            //ByteArrayOutputStream won't happen
        }

        return ous.toByteArray();
    }

    public static String getcodeval(String codetype,String jobnum) {

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(codetype);
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
//        System.out.println(format.format(date));
        stringBuilder.append(jobnum);
        stringBuilder.append(format.format(date));
        return stringBuilder.toString();
    }




    public static void main(String[] args) {
      String codeval = getcodeval("sq","12345678");
      String path = "D:\\important\\项目文件\\输血项目\\temp\\code128\\" + codeval + ".jpg";
      File zipFile = new File(path);
      byte[] generateBarCode128 = generateBarCode128(codeval, null, null, true, false);
      ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
      ByteArrayInputStream in = new ByteArrayInputStream(generateBarCode128);
      BufferedImage bufferImg = null;
      try {
         bufferImg = ImageIO.read(in);
         ImageIO.write(bufferImg, "jpg", byteArrayOut);
         FileOutputStream fos2 = new FileOutputStream(zipFile);
         byteArrayOut.writeTo(fos2);
         fos2.close();
      } catch (IOException e) {
         e.printStackTrace();
      }


    }


}
